import json

from django.http import JsonResponse

from user.models import User


def register(request):
    new_user = json.loads(request.body)
    username = new_user.get('username')
    password = new_user.get('password')
    email = new_user.get('email')
    user = User.objects.create(username=username, password=password, email=email)

    data = {
        'id': user.id,
        'username': user.username,
        'password': user.password,
        'email': user.email
    }
    return JsonResponse({'code': 200, 'message': 'success', 'data': data})


def login(request):
    user = json.loads(request.body)
    username = user.get('username')
    password = user.get('password')
    getuser = User.objects.filter(username=username, password=password)  # 这里添加向User表里insert需要的属性
    # print(getuser)
    if not getuser.exists():
        data = None
        return JsonResponse({'code': 200, 'message': 'failure', 'data': data})
    else:
        getuser = getuser[0]
        data = {
            'id': getuser.id,
            'username': getuser.username,
            'password': getuser.password,
            'email': getuser.email
        }
        return JsonResponse({'code': 200, 'message': 'success', 'data': data})


def info(request, uid):
    user = User.objects.filter(id=uid)
    if user.exists():
        user = user[0]
        data = {
            'id': user.id,
            'username': user.username,
            'password': user.password,
            'email': user.email
        }
        return JsonResponse({'code': 200, 'message': 'success', 'data': data})
    else:
        data = None
        return JsonResponse({'code': 200, 'message': 'Unable to find user info', 'data': data})
